<?php

namespace app\erp\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Brandrule;
use think\Cache;

class Branddb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'brand_id';

    protected $name = 'brand';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'brand_sign',
        'brand_name',
        'audit_state'
    ];

    protected $auto = [
        'initails'
    ];

    // 自动完成英文缩写
    protected function setInitailsAttr($initails)
    {
        return strtoupper($initails);
    }

    protected function setAuditStateAttr($value)
    {
        if ($value) {
            return $value;
        } else {
            if (SITE_ID) {
                // 获取分站信息
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                return 1;
            }
        }
    }

    // 自动完成唯一标识
    protected function setBrandSignAttr()
    {
        return md5(time() . uniqid());
    }

    // 自动完成品牌名称，去除左右空格
    protected function setBrandNameAttr($value)
    {
        return trim($value);
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (!isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    // 查询品牌名称
    public function scopeBrandName($query, $brandName)
    {
        $eq = strpos($brandName,'#');
        if($eq !== false){
            $brandName = str_replace('#', '', $brandName);
            $query->where('brand_name', $brandName);
        } else {
            $query->where('brand_name', 'like', '%' . $brandName . '%');
        }
    }

    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        //$query->where('partner_id', PARTNER_ID);
        // 其他搜索
        if (isset($this->param['brand_name']) && !empty($this->param['brand_name'])) {
            $query->brandName($this->param['brand_name']);
        }
        //只获取军网的品牌
        $sql = Db::name('brand_api')->fetchSql(true)->column('brand_sign');
        $query->whereExp('brand_sign', 'in (' . $sql . ')');
        if (isset($this->param['is_select'])) {
            // 处理分类品牌 未被选取的数据
            $category_brand = new CategoryBranddb();
            $param_cb['category_sign'] = $this->param['category_sign'];
            $category_brand->param = $param_cb;
            $get_category_brand = $category_brand->ajaxSelect();
            if ($get_category_brand['count'] > 0) {
                $get_brand_sign = array();
                foreach ($get_category_brand['data'] as $key => $val) {
                    array_push($get_brand_sign, $val['brand_sign']);
                }
                if ($this->param['is_select'] == 'no') {
                    $query->where('brand_sign', 'NOT IN', $get_brand_sign);
                }
                if ($this->param['is_select'] == 'yes') {
                    $query->where('brand_sign', 'IN', $get_brand_sign);
                }
            } else {
                if ($this->param['is_select'] == 'yes') {
                    $query->where('brand_sign', 'none');
                }
            }
            $query->where('audit_state', 1);
        }
    }

    // 查询
    public function ajaxSelect()
    {
        $return['data'] = $this->ajaxList();
        $return['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxList()
    {
        $data = $this->order($this->param['_o'], $this->param['_b'])
            ->page($this->param['page'], $this->param['limit'])
            ->select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxCount()
    {
        $count = $this
            ->count();
        return $count;
    }

    public function chkFind($brand_name)
    {
        $data = $this->useGlobalScope(false)
            ->where('brand_name', $brand_name)
            ->find();
        if ($data) {
            return $data->toArray();
        } else {
            return array();
        }
    }

    public function ajaxFind($brand_sign, $is_id = false)
    {
        if ($is_id == true) {
            if ($brand_sign) {
                $this->param['brand_id'] = $brand_sign;
            }
            $data = $this->where('brand_id', $this->param['brand_id'])->find();
        } else {
            if ($brand_sign) {
                $this->param['brand_sign'] = $brand_sign;
            }
            if (isset($this->param['brand_sign'])) {
                $data = $this->useGlobalScope(false)
                    ->master()
                    ->where('brand_sign', $this->param['brand_sign'])
                    ->find();
            } else {
                $data = [];
            }
        }
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
            return $data;
        } else {
            return [];
        }
    }

    public function ajaxSaveOne($data, $where)
    {
        $this->save($data, $where);
        Cache::clear('brand');
        return 'success';
    }

    public function ajaxSave()
    {
        $rule = new Brandrule();
        $this->param['partner_id'] = PARTNER_ID;
        if (isset($this->param['brand_sign']) && $this->param['brand_sign'] != '') {
            if (!$rule->scene('edit')->check($this->param)) {
                return $rule->getError();
            }
            unset($this->param['partner_id']);
            $brand_sign = $this->param['brand_sign'];
            $get_last_save_data = $this->ajaxFind($brand_sign);
            unset($this->param['brand_sign']);
            $this->save($this->param, [
                'brand_sign' => $brand_sign
            ]);
            if (SITE_ID && $get_last_save_data['audit_state'] == -1) {
                // 驳回之后修改内容
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    $this->save([
                        'audit_state' => 0
                    ], [
                        'site_id' => SITE_ID,
                        'brand_sign' => $brand_sign
                    ]);
                    $auditdb = new Auditdb();
                    $auditdb->param['audit_method'] = 2;
                    $auditdb->param['audit_type'] = 1;
                    $auditdb->param['site_id'] = SITE_ID;
                    $before_data = $this->param;
                    $auditdb->param['before_option'] = $before_data;
                    $auditdb->param['old_option'] = json_encode($before_data);
                    $after_data = $before_data;
                    $auditdb->param['after_option'] = $after_data;
                    $auditdb->param['audit_sign'] = $brand_sign;
                    $audit_state = $auditdb->ajaxSave();
                }
            }
        } else {
            if (!$rule->check($this->param)) {
                return $rule->getError();
            }
            unset($this->param['partner_id']);
            $get_last_save_data = $this->allowField(true)->save($this->param);
            if (SITE_ID) {
                // 新增 需要验证
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    $auditdb = new Auditdb();
                    $auditdb->param['audit_method'] = 2;
                    $auditdb->param['audit_type'] = 1;
                    $auditdb->param['site_id'] = SITE_ID;
                    $before_data = $this->param;
                    $auditdb->param['before_option'] = $before_data;
                    $auditdb->param['old_option'] = json_encode($before_data);
                    $after_data = $before_data;
                    $auditdb->param['after_option'] = $after_data;
                    $auditdb->param['audit_sign'] = $this->data['brand_sign'];
                    $audit_state = $auditdb->ajaxSave();
                }
            }
        }
        // 添加品牌外部参数
        $brandApidb = new BrandApidb();
        $brandApidb->param['brand_sign'] = $get_last_save_data['brand_sign'];
        $brandApidb->param['option'] = $this->param['api_option'];
        if (isset($this->param['site_id']) && $this->param['site_id']) {
            $brandApidb->param['site_id'] = $this->param['site_id'];
        }
        $brandApidb->ajaxSave();
        Cache::clear('brand');
        return 'success';
    }

    public function ajaxSaveAll()
    {
        $rule = new Brandrule();
        $rule_text = '';
        $rule_flag = 1;
        foreach ($this->param as $key => $val) {
            if (!$rule->check($val)) {
                $rule_flag = 0;
                $rule_text .= $val['brand_name'] . '验证失败：' . $rule->getError() . '<br />';
            }
        }
        if ($rule_flag == 1) {
            $afterAll = $this->saveAll($this->param);
            if (SITE_ID) {
                // 新增 需要验证
                $sitedb = new Sitedb();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site['goods_audit'] == 1) {
                    $auditdb = new Auditdb();
                    $data = array();
                    $afterAll = $afterAll->toArray();
                    foreach ($afterAll as $key => $val) {
                        $temp['audit_method'] = 2;
                        $temp['audit_type'] = 1;
                        $temp['site_id'] = SITE_ID;
                        $temp['before_option'] = $val;
                        $temp['old_option'] = json_encode($temp['before_option']);
                        $temp['after_option'] = $val;
                        $temp['audit_sign'] = $val['brand_sign'];
                        array_push($data, $temp);
                    }
                    $auditdb->param = $data;
                    $return = $auditdb->ajaxSaveAll();
                }
            }
            Cache::clear('brand');
            return 'success';
        } else {
            return $rule_text;
        }
    }

    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['brand_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('brand_id', 'IN', $this->param['brand_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('brand_id', 'IN', $this->param['brand_id']);
                }, true);
            }
            Cache::clear('brand');
            return 'success';
        }
    }

    // 数据处理
    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'brand_picture':
                    $uploaddb = new Uploaddb();
                    if ($val['brand_picture']) {
                        $val['brand_picture_info'] = $uploaddb->getFind($val['brand_picture']);
                    } else {
                        $val['brand_picture_info'] = $uploaddb->getFindTemp();
                    }
                    break;
                default:
                    break;
            }
        }
        $brandApidb = new BrandApidb();
        $brandApidb->param['brand_sign'] = $val['brand_sign'];
        if (isset($this->param['site_id']) && $this->param['site_id']) {
            $brandApidb->param['site_id'] = $this->param['site_id'];
        }
        $api_option = $brandApidb->ajaxFind();
        $val['api_option'] = $api_option['option'];
        return $val;
    }
}